package com.wenjoying.common.api;

import com.wenjoying.common.utils.FunctionUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class BaseController {

    /**运行环境*/
    @Value("${spring.profiles.active:}")
    private String env;

    /**
     * Java一般异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<Exception> exceptionHandler(Exception e){
        e.printStackTrace();
        if (e.getMessage()!=null && e.getMessage().contains("token")) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED.getCode(), e.getMessage(), e);
        }

        return CommonResult.failed(500L, e.getMessage(), e);
    }
    /**
     * Java自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public CommonResult<Exception> exceptionHandler(BaseException e){
        e.printStackTrace();
        if (e.getMessage()!=null && e.getMessage().contains("token")) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED.getCode(), e.getMessage(), e);
        }

        return CommonResult.failed(500L, e.getMessage(), e);
    }

    /**
     * IP限制
     * @param request
     * @return
     */
    public Boolean checkIp(HttpServletRequest request) {
        if ("pro".equals(env) || "prod".equals(env)) {
            String ip = FunctionUtil.getIpAddress(request);
            List<String> list = new ArrayList<>();
            //scrm正式IP
            list.add("61.172.57.230");
            //scrm测试IP
            list.add("47.103.69.216");

            if (!list.contains(ip)) {
                return false;
            }
        }

        return true;
    }
}
